const {app, BrowserWindow, Menu, ipcMain,shell,Notification} = require('electron')
const path = require('path')
const eggLauncher = require('./electron/lanucher')
const setup = require('./electron/setup')
const electronConfig = require('./electron/config')
const storage = require('./electron/storage')
const is = require('electron-is')
const setTray = require('./electron/tray')
const electron = require('electron')
const robot = require("robotjs");   //控制鼠标键盘等操作
const exec = require('child_process').exec
const puppeteer = require('puppeteer')
// console.log('------------------------------------------------------------')
console.info(process.versions)
// console.log('------------------------------------------------------------')
// Enable live reload for all the files inside your project directory

//开发环境
if (process.env.NODE_ENV == 'production') {
  require('electron-reload')(__dirname);
}

// main window
global.MAIN_WINDOW = null
global.APP_TRAY = null;
global.CAN_QUIT = false;

// 限制只可以打开一个应用, 4.x的文档
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
    if (MAIN_WINDOW) {
      if (MAIN_WINDOW.isMinimized()) MAIN_WINDOW.restore()
      MAIN_WINDOW.focus()
      MAIN_WINDOW.show()
    }
  })
  // 创建 myWindow, 加载应用的其余部分, etc...
  // app.on('ready', () => {
  // })
}

// Initialize 
setup()
//return

// argv
let ENV = 'prod'
var newWin = null; 
for (let i = 0; i < process.argv.length; i++) {
  const tmpArgv = process.argv[i]
  if (tmpArgv.indexOf('--env=') !== -1) {
    ENV = tmpArgv.substr(6)
  }
}
const eggConfig = electronConfig.get('egg', ENV)
eggConfig.env = ENV
if (process.mas) app.setName('electron-egg')
async function initialize () {
  app.whenReady().then(() => {
    createWindow()
    app.on('activate', function () {
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })
  })
  
  app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') {
      console.log('window-all-closed quit')
      app.quit()
    } 
  })
  
  // 创建一个新窗口
  ipcMain.on('opn-win', () => {
	  if(newWin) return
    //调用 BrowserWindow打开新窗口
	newWin =new BrowserWindow({
		width: 800,
		height: 1000,
		minWidth: 800,
		minHeight: 1000,
		x:1020,
		y:200,
		webPreferences: {
		  //webSecurity: false,
		  contextIsolation: false, // 设置此项为false后，才可在渲染进程中使用electron api
		  nodeIntegration: true,
		},
		// backgroundColor: '#FFFF00' // background color
		frame: false,
		titleBarStyle: '#FFFF00'
	})
	//打开一个新的窗口
	// newWin.loadURL(`file://${__dirname}/otherWin.html`);
	//新建窗口
	newWin.loadURL(`file://${__dirname}/asset/wechat-window.html`);
	// 3. 关闭窗口
	ipcMain.on('window-close',function (){
	  if(newWin) {
		  var screenSize = robot.getScreenSize();
		  console.log(screenSize.width,screenSize.height)
		  // robot.moveMouse(1229, 251);	//移动鼠标
		  // setTimeout(function() {
			 //  robot.mouseClick('left',true);	 //鼠标点击
		  // }, 500);
		  newWin.close();
		  newWin=null
	  }
	})
  })
  
  // 进入自动化
  //鼠标点击登录
  ipcMain.on('openOperate', async () => {
	  // Or import puppeteer from 'puppeteer-core';
	    
		const browser = await puppeteer.launch({ headless: false })

		const page = await browser.newPage();

		// Navigate the page to a URL.
		await page.goto('https://mobile.pinduoduo.com/');
	  
	  // Set screen size.
	  await page.setViewport({width: 1080, height: 1024});
	  
	  // Type into search box.
	  // await page.locator('.devsite-search-field').fill('automate beyond recorder');
	  
	  // Wait and click on first result.
	  await page.locator('#main > div > div.rByMBUmP > div:nth-child(4) > div > div.footer-items > div:nth-child(5)').click();
	  await page.locator('#first > div.login-box > div').click();
	  
	  const NOTIFICATION_TITLE = '请输入手机号'
	  const NOTIFICATION_BODY = '请输入手机号和验证码后点击登录'
		new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show()


		await page.evaluate(() => {
					console.log('控制台输入成功')  
				  });
		

	  await page.locator('#main > section > div.order-menu > div.order-title > div.others').click();
	  
	  
		  await page.evaluate(() => {
			  
			  // var script = document.createElement("script");
			  // script.src = "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js";
			  // document.getElementsByTagName('head')[0].appendChild(script);// 验证是否引入成功>jQueryƒ (e,t){return new k.fn.init(e,t)}

			
			
			// let state = 3 //待收货：3 ，全部：0 ，待付款：1 ，待分享：5 ，待发货：2，评价：4
			
			// var scrollBottom = setInterval(scrollToBottom, 500);
			//     function scrollToBottom() {
			      
			// var tisp = $('.loading-text').text();
			//         console.log(tisp)
			//         if(tisp.indexOf("没找到订单？试试")!=-1){
			//             var order = [];
			//             clearInterval(scrollBottom);
			//             var listOrder = $(`#base-list${state}>.react-base-list`).children();
			            
			//             $.each(listOrder,function(index,row){
			//                 order.push($(row)[0].innerText.split('\n\n'))
			//                 if(index == listOrder.length - 1){
			//                     let orderlist = '店铺名称,交易状态,商品名称,价格,数量,实际付款,确认收货后自动付款\r\n'
			//                     $.each(order,function(index1,row1){
			//                         console.log(row1)
			//                         if(row1.length == 9){
			//                             let price = row1[4].split('\n');
			//                             orderlist += `${row1[0].replace(/\r|\n|\r\n|\n\r|\t|,/ig,"") +','+ row1[1] +','+ row1[2].replace(/\r|\n|\r\n|\n\r|\t|,/ig,"") +','+ row1[3].replace(/\r|\n|\r\n|\n\r|\t|,/ig,"")+','+price[0] +','+ price[1] +','+ row1[6] }\r\n`
			//                         }else{
			//                             let price = row1[4].split('\n');
			//                             let rellaPrice = row1[7].split('¥')[1]
			//                             if(!rellaPrice) {
			//                                 rellaPrice = '商品为实际付款'
			//                             } else {
			//                                 rellaPrice = rellaPrice.replace(')','')
			//                             }
			//                             orderlist += `${row1[0].replace(/\r|\n|\r\n|\n\r|\t|,/ig,"") +','+ row1[1] +','+ row1[2].replace(/\r|\n|\r\n|\n\r|\t|,/ig,"") +','+price[0] +','+ price[1] +','+ row1[6]+','+ rellaPrice }\r\n`
			//                         }
			//                         if(index1 == order.length - 1){
			//                             const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(orderlist);
			//                             const link = document.createElement("a");
			//                             link.href = uri;
			//                             link.download = `${'拼多多订单数据' + '.csv'}`;
			//                             link.click();
			//                         }
			//                     })
			//                 }
			//             })
			//         }
			//       $("html, body").animate({ scrollTop: $(document).height() }, 500);
			//     }
			



		    // window.scrollTo(0, document.body.scrollHeight);
		  });
	  
	  // Locate the full title with a unique string.
	  const textSelector = await page
	    .locator('text/Customize and automate')
	    .waitHandle();
	  const fullTitle = await textSelector?.evaluate(el => el.textContent);
	  
	  // Print the full title.
	  console.log('The title of this blog post is "%s".', fullTitle);
	  
	  await browser.close();
  })
  
  
  //鼠标点击登录
  ipcMain.on('loginClick', () => {
	  shell.openExternal('https://mobile.pinduoduo.com/')
	   
	   setTimeout(() => {
	   	  {
			  robot.keyTap("f12");
			  // 模拟按下 Control 和 Shift  
			  robot.keyToggle("control", "down");  
			  robot.keyToggle("shift", "down");  
			    
			  // 稍微延时一下（可选，取决于你的应用程序）  
			  // 注意：robotjs 没有内置的延时函数，你需要自己实现或使用其他库  
			  // 这里只是示意，实际上你可能不需要延时  
			  // setTimeout(() => {  
			  //     // 执行你的操作  
			  // }, 100); // 延时100毫秒  
			    
			  // 模拟按下并释放 M  
			  robot.keyTap("m");  
			    
			  // 释放 Control 和 Shift  
			  robot.keyToggle("control", "up");  
			  robot.keyToggle("shift", "up");
			  
			  setTimeout(() => {
			  			   robot.keyTap("l","control");  
			  },2000)
		  }
		  
			{
				setTimeout(() => {
					{
								  // 模拟按下 Control 和 Shift
								  robot.keyToggle("alt", "down");  
								  robot.keyToggle("space", "down");  
								    
								  // 稍微延时一下（可选，取决于你的应用程序）  
								  // 注意：robotjs 没有内置的延时函数，你需要自己实现或使用其他库  
								  // 这里只是示意，实际上你可能不需要延时  
								  // setTimeout(() => {  
								  //     // 执行你的操作  
								  // }, 100); // 延时100毫秒  
								    
								  // 模拟按下并释放 M  
								  robot.keyTap("x");  
								    
								  // 释放 Control 和 Shift  
								  robot.keyToggle("alt", "up");  
								  robot.keyToggle("space", "up");
					}
					
					
					
					
					
				},3000)
				
				setTimeout(i => {
						  robot.moveMouseSmooth(1759, 419);
						  robot.mouseClick();	 //鼠标点击
						  
						  robot.typeString(`var script = document.createElement("script");
						  script.src = "https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js";
						  document.getElementsByTagName('head')[0].appendChild(script);// 验证是否引入成功>jQueryƒ (e,t){return new k.fn.init(e,t)}
						  `);
				},3500)
			}
	   },3000)
	  // penDefaultBrowser('https://www.baidu.com')
   // robot.moveMouseSmooth(1207, 726);
   // setTimeout(() => {
	  //  robot.mouseClick();	 //鼠标点击
   // },3000)
  })
	
	ipcMain.on('close-app', () => {
	  if (MAIN_WINDOW) {
		MAIN_WINDOW.close()
	  }
	})
	ipcMain.on('min-app', () => {
	  MAIN_WINDOW.minimize()
	})
	
	// 拖动鼠标保存二维码
	ipcMain.on('dragMouse', (event,arg) => {
	  exec('echo wechat | clip');
      robot.moveMouseSmooth(189, 1062);
	  robot.mouseClick();	 //鼠标点击
	  setTimeout(i => {
		 robot.keyTap("v", "control");
		 // robot.typeString("wechat")
	  },2000)
	  setTimeout(i => {
		  robot.moveMouseSmooth(225, 513);
		  robot.mouseClick();	 //鼠标点击
	  },3500)
	  setTimeout(i => {
		  robot.moveMouseSmooth(189, 1062);
		  robot.mouseClick();	 //鼠标点击
		  exec('echo 蒲公英自动化上传工具 | clip');
	  },5000)
	  setTimeout(i => {
		 robot.keyTap("v", "control");
		 // robot.typeString("wechat")
	  },7000)
	  setTimeout(i => {
		  robot.moveMouseSmooth(225, 513);
		  robot.mouseClick();	 //鼠标点击
	  },9000)
	  setTimeout(i => {
		  //发送微信
		  enterWechat()
	  },10000)
	})
	
	 ipcMain.on('max-app', (event, arg) => {
	    // 判断窗口是否已经最大化
	       if(arg==1){
	           // 最大化
	           MAIN_WINDOW.maximize()
	       }else{
			   // 窗口还原
			   MAIN_WINDOW.restore()
	       }
	 })
   
ipcMain.on('synchronous-message', (event, arg) => {
	// console.log(window.location)
	// //调用 BrowserWindow打开新窗口
	// newWin =new BrowserWindow({
	// 	width:500,
	// 	height:500,
	// 	frame:true,//是否显示边缘框
	// 	fullscreen:false //是否全屏显示
	// })
	// //  //新建窗口
	// newWin.loadURL();
	// newWin.on('close',()=>{
	// 	newWin=null
	// })
	// console.log(arg) // prints "ping"
	event.returnValue = 'pong'
  })

  // Open url with the default browser
  // app.on('web-contents-created', (e, webContents) => {
  //   webContents.on('new-window', (event, url) => {
  //       event.preventDefault()
  //       shell.openExternal(url)
  //   });
  // });
}

async function createWindow () {
  MAIN_WINDOW = new BrowserWindow(electronConfig.get('windowsOption'))
  
  // if (process.platform === 'linux') {
  //   windowOptions.icon = path.join(__dirname, '/assets/app-icon/png/512.png')
  // }
  
//生产环境
  if (eggConfig.env === 'prod') {
    // hidden menu
    Menu.setApplicationMenu(null)

    // dynamic port
    await storage.setDynamicPort()
    eggConfig.port = electronConfig.get('egg', eggConfig.env).port
  }

  // loding page
  MAIN_WINDOW.loadURL(path.join('file://', __dirname, '/asset/loading.html'))
  
  // tray 
  setTray();

  // egg server
  await startServer(eggConfig)

  // check update
  const updateConfig = electronConfig.get('autoUpdate')
  if ((is.windows() && updateConfig.windows) || (is.macOS() && updateConfig.macOS)
    || (is.linux() && updateConfig.linux)) {
    const autoUpdater = require('./electron/autoUpdater');
    autoUpdater.checkUpdate();
  }

  return MAIN_WINDOW
}

async function startServer (options) {
  ELog.info('[main] [startServer] options', options)
  const protocol = 'http://'
  let startRes = null
  let url = null
  if (ENV === 'prod') {
    url = protocol + options.hostname + ':' + options.port
  } else {
    const developmentModeConfig = electronConfig.get('developmentMode', ENV)
    const selectMode = developmentModeConfig.default
    const modeInfo = developmentModeConfig.mode[selectMode]
    switch (selectMode) {
      case 'vue' :
        url = protocol + modeInfo.hostname + ':' + modeInfo.port
        break
      case 'react' :
        url = protocol + modeInfo.hostname + ':' + modeInfo.port
        break
      case 'ejs' :
        url = protocol + modeInfo.hostname + ':' + modeInfo.port
        break
    }
  }
  ELog.info('[main] [url]:', url)
  startRes = await eggLauncher.start(options).then((res) => res, (err) => err)
  ELog.info('[main] [startServer] startRes:', startRes)
  if (startRes === 'success') {
    MAIN_WINDOW.loadURL(url)
    return true
  }
  
  app.relaunch()
}


//发送微信文件传输助手o
function enterWechat() {
	  //Mouse down at 0, 0 and then drag to 100, 100 and release.
	  robot.moveMouseSmooth(1440, 240);
	  robot.mouseToggle("down");
	  // robot.dragMouse(1541, 673);
	  // robot.moveMouse(1541, 673);	//移动鼠标
	  
	  
	  setTimeout(i => {
		  robot.mouseToggle("up");
		  robot.moveMouseSmooth(1370, 430);
		  robot.mouseToggle("down");
		  robot.dragMouse(856, 434);
		  robot.mouseToggle("up");
		  robot.keyTap("c", "control");
	  },1500)
	  
	  setTimeout(i => {
		  //Mouse down at 0, 0 and then drag to 100, 100 and release.
		  robot.moveMouseSmooth(1440, 800);
		  robot.mouseToggle("down");
		  // robot.dragMouse(1541, 673);
		  // robot.moveMouse(1541, 673);	//移动鼠标
	  },3000)
	  
	  setTimeout(i => {
		  robot.mouseToggle("up");
		  robot.moveMouseSmooth(1611, 284);
		  robot.mouseClick();	 //鼠标点击
	  },5000)
	  
	  setTimeout(i => {
		  robot.moveMouseSmooth(1200, 297);
		  robot.mouseClick();	 //鼠标点击
	  },7000)
	  
	  setTimeout(i => {
		  robot.keyTap("v", "control");
		  robot.moveMouseSmooth(1223, 384);
	  },9000)
	  setTimeout(i => {
		  robot.mouseClick();	 //鼠标点击
	  },11000)
	  
	  setTimeout(i => {
		  robot.keyTap("a", "alt");
		  robot.moveMouseSmooth(783, 548);
		  robot.mouseToggle("down");
		  robot.dragMouse(1028, 793);
		  
	  },13000)
	  
	  setTimeout(i => {
		  robot.mouseToggle("up");
		  robot.keyTap("enter");
		  robot.moveMouseSmooth(1505, 673);
		  robot.mouseClick();	 //鼠标点击
		  robot.keyTap("v", "control");
		  robot.keyTap("enter");
		  robot.keyTap("enter");
	  },15000)

	  // Press enter.
	  // setTimeout(item => {
		 //  robot.keyTap("c", "control");
	  // },500)
}

let type = 0
//创建一个事件监视程序
function StartWatcher(path){
      var chokidar = require("chokidar");

      var watcher = chokidar.watch(path, {
          ignored: /(^|[\/\\])\../, persistent: true
      });

      function onWatcherReady(){
          console.info('From here can you check for real changes, the initial scan has been completed.');
      }
            
      // Declare the listeners of the watcher
      watcher
      .on('add', function(path) {
		  
		  // var screenshot = require('screenshot-desktop')
		   
		  // absolute paths work too. so do pngs
		  // screenshot({ filename: 'screen-img/screenshot.png' })
		  // var screenSize = robot.getScreenSize();
		  // robot.moveMouseSmooth(screenSize.width-950, screenSize.height-1047);	//移动鼠标
		 if(type!=0)  {
		    exec('echo 蒲公英自动化上传工具 | clip');
			 setTimeout(i => {
			 		  robot.moveMouseSmooth(189, 1062);
			 		  robot.mouseClick();	 //鼠标点击
			 },1000)
			 setTimeout(i => {
			 		 robot.keyTap("v", "control");
			 		 // robot.typeString("wechat")
			 },2500)
			 setTimeout(i => {
			 		  robot.moveMouseSmooth(225, 513);
			 		  robot.mouseClick();	 //鼠标点击
			 },3500)
			 setTimeout(function() {
			 	  robot.moveMouseSmooth(1440, 245);	//移动鼠标
			 	  robot.mouseToggle("down");
			   },4500)
			   setTimeout(function() {
				   robot.mouseToggle("up");
				 robot.moveMouseSmooth(1188, 568);
			   },9000)
			   setTimeout(function() {
			   		 robot.mouseClick();	 //鼠标点击
			   },12000)
			 setTimeout(function() {
				 robot.moveMouseSmooth(862, 367);
			 	// robot.keyTap('backspace');
			 	// robot.keyTap('capslock');
			 	// robot.typeStringDelayed('xinjian', 100);//第二个参数的官方解释为每分钟敲击的字符数，理论上数字越大速度越快
			 	// robot.keyTap('capslock');
			 	// robot.keyTap('enter');
			 	// robot.keyTap('enter');
			 },16000)
			   setTimeout(function() {
				 robot.mouseClick();	 //鼠标点击
				 robot.mouseClick();	 //鼠标点击
			   },20000)	
			   setTimeout(function() {
			 	 // robot.moveMouseSmooth(1342, 237);	//移动鼠标
			 	 // robot.mouseClick();	 //鼠标点击
			   },8500)	
			   // robot.setMouseDelay(50)	
			   // robot.moveMouse(1424, 387);
			   // robot.mouseToggle("down");
			   // robot.dragMouse(1422, 676);
			   // robot.mouseToggle("up");
			   // robot.setMouseDelay(50)	
			   // MAIN_WINDOW.send('on-file-message', path);
		 }
		 type +=1
            console.log('File', path, 'has been added');
      })
      .on('addDir', function(path) {
            console.log('Directory', path, 'has been added');
      })
      .on('change', function(path) {
           console.log('File', path, 'has been changed');
      })
      .on('unlink', function(path) {
           console.log('File', path, 'has been removed');
      })
      .on('unlinkDir', function(path) {
           console.log('Directory', path, 'has been removed');
      })
      .on('error', function(error) {
           console.log('Error happened', error);
      })
      .on('ready', onWatcherReady)
      .on('raw', function(event, path, details) {
           // This event should be triggered everytime something happens.
           console.log('Raw event info:', event, path, details);
      });
}

ipcMain.on('on-file-path', (event, arg) => {
 //启动监视程序
 // StartWatcher(path[0]);
 StartWatcher(arg); //测试
  // event.returnValue = ''
})


initialize()